package com.hht.downloadmanager.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;

import com.hht.downloadmanager.bean.FileBean;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class FilesUtil {

    // 关闭资源
    public static void closeable(Closeable... closeables) {
        int length = closeables.length;
        if (length < 1) {
            return;
        }
        try {
            for (int i = 0; i < length; i++) {
                Closeable closeable = closeables[i];
                if (null != closeable) {
                    closeable.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            for (int i = 0; i < length; i++) {
                closeables[i] = null;
            }
        }
    }


    // 删除临时文件
    public static void cleanFile(File... files) {
        int length = files.length;
        if (length < 1) {
            return;
        }
        for (int i = 0; i < length; i++) {
            if (null != files[i])
                files[i].delete();
        }
    }

    /**
     * 确认下载状态
     *
     * @param count
     * @return
     */
    public static boolean confirmStatus(AtomicInteger count, FileBean bean) {
        int curNumber = count.incrementAndGet();
        boolean status = (curNumber % bean.getThreadNumber() != 0);
        return status;
    }

    public static String getDefaultFilePath(Context context) {
        File sdDir;
        // 判断sd卡是否存在
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);

        if (sdCardExist) {
            if (Build.VERSION.SDK_INT>=29){
                //Android10之后
                sdDir = context.getExternalFilesDir(null);
            }else {
                sdDir = Environment.getExternalStorageDirectory();// 获取SD卡根目录
            }
        } else {
            sdDir = Environment.getRootDirectory();// 获取跟目录
        }

//        return Environment.getExternalStorageDirectory().getAbsolutePath()
//                + File.separator + "DownLoadFiles";
        return sdDir.getAbsolutePath()+ File.separator + "DownLoadFiles";
    }

    public static String getDefaultFileName(String url) {
        String name = "downloadName";
        try {
            name = url.substring(url.lastIndexOf("/") + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }
}
